﻿function FixTable(TableID, FixColumnNumber, width, height) {
            var issort = true;
			if ($("#" + TableID + "_tableLayout").length != 0) {
				$("#" + TableID + "_tableLayout").before($("#" + TableID));
				$("#" + TableID + "_tableLayout").empty();
			}
			else {
				$("#" + TableID).after("<div id='" + TableID + "_tableLayout' style='overflow:hidden;height:" + height + "px; width:" + width + "px;'></div>");
			}

			$('<div id="' + TableID + '_tableFix"></div>'
			+ '<div id="' + TableID + '_tableHead"></div>'
			+ '<div id="' + TableID + '_tableColumn"></div>'
			+ '<div id="' + TableID + '_tableData"></div>').appendTo("#" + TableID + "_tableLayout");


			var oldtable = $("#" + TableID);

			var tableFixClone = oldtable.clone(true);
			tableFixClone.attr("id", TableID + "_tableFixClone");
			$("#" + TableID + "_tableFix").append(tableFixClone);
			var tableHeadClone = oldtable.clone(true);
			tableHeadClone.attr("id", TableID + "_tableHeadClone");
			$("#" + TableID + "_tableHead").append(tableHeadClone);
			var tableColumnClone = oldtable.clone(true);
			tableColumnClone.attr("id", TableID + "_tableColumnClone");
			$("#" + TableID + "_tableColumn").append(tableColumnClone);
			$("#" + TableID + "_tableData").append(oldtable);

			$("#" + TableID + "_tableLayout table").each(function () {
			$(this).css({ "margin": "0", "width": width-17 });
			});


			var HeadHeight = $("#" + TableID + "_tableHead thead").height();
			HeadHeight += 2;
			$("#" + TableID + "_tableHead").css("height", HeadHeight);
			$("#" + TableID + "_tableFix").css("height", HeadHeight);


			var ColumnsWidth = 0;
			var ColumnsNumber = 0;

			if ($("#" + TableID + "_tableColumn tr td").length > 0) {
			    if (FixColumnNumber > 0) {
			        $("#" + TableID + "_tableColumn tr:last td:lt(" + FixColumnNumber + ")").each(function() {
			            ColumnsWidth += $(this).outerWidth(true);
			            ColumnsNumber++;
			        });
			    } else {
			        $("#" + TableID + "_tableColumn tr:last td").each(function() {
			            ColumnsWidth += $(this).outerWidth(true);
			            ColumnsNumber++;
			        });
			    }
			}
			else {
			    $("#" + TableID + "_tableColumn tr th").each(function() {
			        ColumnsWidth += $(this).outerWidth(true);
			        ColumnsNumber++;
			    });
			}
              ColumnsWidth += 2;

              if ($.browser.msie) {
                  switch ($.browser.version) {
                      case "7.0":
                          if (ColumnsNumber >= 3) ColumnsWidth--;
                          break;
                      case "8.0":
                          if (ColumnsNumber >= 2) ColumnsWidth--;
                          break;
                  }
              }
             
              if (FixColumnNumber > 0) {
                  $("#" + TableID + "_tableColumn").css("width", ColumnsWidth);
              } else {
                  $("#" + TableID + "_tableColumn").css("width", 0);
              }
              $("#" + TableID + "_tableFix").css("width", ColumnsWidth);


              $("#" + TableID + "_tableData").scroll(function() {
                  $("#" + TableID + "_tableHead").scrollLeft($("#" + TableID + "_tableData").scrollLeft());
                  $("#" + TableID + "_tableColumn").scrollTop($("#" + TableID + "_tableData").scrollTop());
              });

              $("#" + TableID + "_tableFix").css({ "overflow": "hidden", "position": "relative", "z-index": "50", "background-color": "Silver" });
              $("#" + TableID + "_tableHead").css({ "overflow": "hidden", "width": width , "position": "relative", "z-index": "45", "background-color": "Silver" });
              $("#" + TableID + "_tableColumn").css({ "overflow": "hidden", "height": height-17, "position": "relative", "z-index": "40", "background-color": "Silver" });
              $("#" + TableID + "_tableData").css({ "overflow": "auto", "width": width, "height": height, "position": "relative", "z-index": "35" });

              if ($("#" + TableID + "_tableHead").width() > $("#" + TableID + "_tableFix table").width()) {
                  $("#" + TableID + "_tableHead").css("width", $("#" + TableID + "_tableFix table").width());
                  $("#" + TableID + "_tableData").css("width", $("#" + TableID + "_tableFix table").width() + 17);
              }
              if ($("#" + TableID + "_tableColumn").height() > $("#" + TableID + "_tableColumn table").height()) {
                  $("#" + TableID + "_tableColumn").css("height", $("#" + TableID + "_tableColumn table").height());
                  $("#" + TableID + "_tableData").css("height", $("#" + TableID + "_tableColumn table").height() + 17);
              }
              if ($("#" + TableID + "_tableData table").height() > $("#" + TableID + "_tableData").height()) {
                  $("#" + TableID + "_tableFix").css("width", $("#" + TableID + "_tableHead").width());
              } 
              
              if ($.browser.mozilla) {
                  $("#" + TableID + "_tableData table").css("width", $("#" + TableID + "_tableFix table").width());
                 
              }
              $("#" + TableID + "_tableFix").offset($("#" + TableID + "_tableLayout").offset());
              $("#" + TableID + "_tableHead").offset($("#" + TableID + "_tableLayout").offset());
              $("#" + TableID + "_tableColumn").offset($("#" + TableID + "_tableLayout").offset());
              $("#" + TableID + "_tableData").offset($("#" + TableID + "_tableLayout").offset());
           
              if (issort) {
                  $("#" + TableID).sortFixtable({ ascImgUrl: "/res/img/bullet_arrow_up.png",
                      descImgUrl: "/res/img/bullet_arrow_down.png",
                      ascImgSize: "10px",
                      descImgSize: "10px",
                      onSorted: function(cell) {
                          $("#" + TableID + " tbody tr").click(function() {
                              OnAcceptSelect($(this));

                          });
                          tb_Reloadinit();
                      }

                  });
                
               }
          }




          $.fn.extend({
              sortFixtable: function(setting) {
                  // 配置参数
                  var configer = $.fn.extend({
                      // 属性
                      sorttingMsg: "排序中……",
                      sorttingMsgColor: "#FFF",
                      allowMask: true,
                      maskOpacity: "0.5",
                      maskColor: "#000",
                      ascImgUrl: "",
                      ascImgSize: "8px",
                      descImgUrl: "",
                      descImgSize: "8px",
                      headTable: "",

                      // 事件
                      onSorted: null // 排序完成回调函数
                  }, setting);

                  // 获取扩展对象
                  var extObj = $(this);
                  // 用于锁住当前操作的对象
                  var lock = false;
                  // 排序属性的可取值
                  var sortOrder = {
                      byAsc: "asc",
                      byDesc: "desc"
                  };
                  // 自定义属性名
                  var myAttrs = {
                      order: "order",
                      by: "by",
                      sort: "sort"
                  };
                  // 可排序行的头列（jquery对象——集合）
                  var headCells = $($(this).selector + "_tableFixClone").find("tr[role='head']>[" + myAttrs.sort + "='true']");
                  headCells.each(function() {
                      if (configer.ascImgUrl != "" && configer.descImgUrl != "") {
                          $("&nbsp;<img class='asc' src='" + configer.ascImgUrl + "' style='width:" + configer.ascImgSize + "; height:" + configer.ascImgSize + ";display:none;' title='升序' alt='升序'/>").appendTo($(this));
                          $("&nbsp;<img class='desc' src='" + configer.descImgUrl + "' style='width:" + configer.descImgSize + "; height:" + configer.descImgSize + ";display:none;' title='降序' alt='降序'/>").appendTo($(this));
                      }
                      else {
                          $("&nbsp;<span class='asc' style='width:12px; height:12px;display:none;' title='升序'>&#118;</span>").appendTo($(this));
                          $("&nbsp;<span class='desc' style='width:12px; height:12px;display:none;' title='降序'>&#94;</span>").appendTo($(this));
                      }
                      $(this).css("cursor", "default");
                  });

                  // 设置头列点击事件
                  $($(this).selector + "_tableFixClone").find("tr[role='head']>[" + myAttrs.sort + "='true']").click(function() {
                      var thisHeadCell = $(this);
                      var thisCurrentCellIndex = $(this)[0].cellIndex;
                      var thisCell = $($(extObj).selector + "_tableData").find("tr[role='head'] th:eq(" + thisCurrentCellIndex + ")");
                      //                      var thisCell=
                      if (lock == false) {
                          lock = true; // 锁事件

                          if (configer.allowMask) {
                              var tw = extObj.outerWidth();
                              var th = extObj.parent("div").height(); // extObj.outerHeight();
                              var tOffSet = extObj.offset();
                              var tTop = tOffSet.top;
                              var tLeft = tOffSet.left;
                              // 添加遮罩层
                              var mark = $("<div></div>").attr("id", "TableSort_Mark").css("background-color", configer.maskColor).css("position", "absolute").css("top", tTop + "px").css("left", tLeft + "px").css("opacity", configer.maskOpacity).css("z-index", "9999").css("width", tw + "px").css("height", th + "px");
                              mark.html("<h3 id='TableSort_Sortting' style='opacity:1;color:" + configer.sorttingMsgColor + ";padding:36px 0 0 0;text-align:center;'>" + configer.sorttingMsg + "</h3>");
                              mark.appendTo($("body"));

                              // 延时执行排序方法，显示遮罩层需要时间~
                              window.setTimeout(function() {
                                  // 设置列排序
                                  SetColumnOrder(thisCell, thisHeadCell);
                                  // 触发排序完成回调函数
                                  FireHandleAfterSortting(thisCell);

                                  // 解锁，撤销遮罩层
                                  lock = false;
                                  mark.remove();

                              }, 100);
                          }
                          else {
                              // 设置列排序
                              SetColumnOrder(thisCell, thisHeadCell);
                              // 触发排序完成回调函数
                              FireHandleAfterSortting(thisCell);

                              // 解锁，撤销遮罩层
                              lock = false;
                          }

                          // 所有头部的列的排序标记设置为false
                          headCells.attr(myAttrs.order, false);
                          // 被点击列的排序标志设置为true
                          thisHeadCell.attr(myAttrs.order, true);
                          // 设置排序列的排序规则
                          var by = thisHeadCell.attr(myAttrs.by);
                          thisHeadCell.attr(myAttrs.by, (by == sortOrder.byAsc ? sortOrder.byDesc : sortOrder.byAsc));

                      }
                  });

                  //====================================
                  // 说明：触发排序完成回调函数
                  // 参数：sortCell = 当前排序的列头
                  //------------------------------------
                  function FireHandleAfterSortting(sortCell) {
                      if (configer.onSorted != null) {
                          configer.onSorted(sortCell);
                      }
                  }

                  //====================================
                  // 说明：设置列排序
                  // 参数：headCell = 列头（jquery对象）
                  //------------------------------------
                  function SetColumnOrder(headCell, headclick) {
                      var by = headclick.attr(myAttrs.by);
                      var index = headCell.index();
                      var rs = extObj.find("tr[role!='head']");
                      rs.sort(function(r1, r2) {
                          var a = $.trim($(r1).children("td").eq(index).text());
                          var b = $.trim($(r2).children("td").eq(index).text());
                          if (a == b) {
                              return 0;
                          }

                          var isDt = IsTime(a) && IsTime(b);

                          if (isDt) {
                              var dt1 = new Date(a.replace(/-/g, "/"));
                              var dt2 = new Date(b.replace(/-/g, "/"));
                              if (dt1.getTime() > dt2.getTime()) {
                                  return (by == sortOrder.byAsc) ? 1 : -1;
                              }
                              else {
                                  return (by == sortOrder.byAsc) ? -1 : 1;
                              }
                          }
                          else if (isNaN(a) || isNaN(b)) {
                              return (by == sortOrder.byAsc) ? a.localeCompare(b) : b.localeCompare(a);
                          }
                          else {

                              if (a - b > 0) {
                                  return (by == sortOrder.byAsc) ? 1 : -1;
                              }
                              else {
                                  return (by == sortOrder.byAsc) ? -1 : 1;
                              }
                          }
                      });
                      extObj.find("tr[role!='head']").remove();
                      extObj.append(rs);
                      // 显示箭头排序列图标
                     headclick.parent().parent().children("tr:eq(0)").find("th").each(function() {
                      $(this).children(".asc,.desc").hide();
                        });
                      if (by == sortOrder.byAsc) {
                          headclick.children(".asc").show();
                      }
                      else {
                          headclick.children(".desc").show();
                      }
                  }

                  //================================================
                  // 说明：判断字符串是否是时间
                  //------------------------------------------------
                  function IsTime(dateString) {
                      dateString = $.trim(dateString);
                      if (dateString == null && dateString.length == 0) {
                          return false;
                      }

                      dateString = dateString.replace(/\//g, "-");
                      var reg = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/;
                      var r = dateString.match(reg);
                      if (r == null) {
                          var reg = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/;
                          var r = dateString.match(reg);
                      }

                      return r != null;
                  }
              }
          });
